package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.Message;
import model.MessageDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: DELL
 * Date: 2023-03-27
 * Time: 9:22
 */


@WebServlet("/message")
public class MessageServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        // 解析 发来的 message:message 字段 放到message中
        Message message = objectMapper.readValue(req.getInputStream(), Message.class);
        resp.setContentType("application/json; charset = utf8");
        Message message1 = new Message();
        message1.setMessage(message.getMessage());
        MessageDao messageDao = new MessageDao();
        messageDao.save(message1);
        resp.setStatus(200);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json; charset = utf8");
        MessageDao messageDao = new MessageDao();
        List<Message> messageList = messageDao.load();
        // 把 java 对象转为 json 对象
        ObjectMapper objectMapper = new ObjectMapper();
        String respJson = objectMapper.writeValueAsString(messageList);
        resp.getWriter().write(respJson);
    }
}
